<template>
  <div class="ql-editor-wrapper ql-editor-wrapperStyle">
    <div class="editor-top" style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px">
      <div>
        <div class="labels" style="display: flex; align-items: center">
          <p></p>
          设置模板变量
          <div class="tips" style="margin-bottom: 0; margin-left: 12px">快速添加员工姓名、部门、岗位等信息，内容中会自动替换为真实信息</div>
        </div>
      </div>
      <a-button type="primary" ghost style="margin-right: 270px" @click="onPreview" :loading="previewBtn">在线预览</a-button>
    </div>
    <div class="ql-editor-content ql-editor-content2" style="padding-left: 24px; padding-right: 318px">
      <div id="editor-main" class="editor-main" style="padding: 0">
        <div style="width: 936px; margin: 0 auto">
          <vue-wangeditor ref="editor" v-model="content" :menus="menus" :height="editorHeight" />
        </div>
      </div>
      <div
        class="editor-config editor-config2"
        style="border: 0; z-index: 10; background: #fff; padding: 0; width: 280px; overflow: none; overflow: inherit"
      >
        <div class="mb12" style="margin-top: -44px">
          <a-input-search v-model="varQuery" allowClear placeholder="输入关键字" style="width: 250px" @search="debouncedSearch" />
        </div>
        <div class="editor-config-block" style="border: 0; overflow: auto; height: calc(100% - 12px)">
          <div class="editor-config-block-content" style="margin-top: 0">
            <div v-for="(item, index) in variables" :key="index">
              <div v-if="item.title === '员工个人信息'">
                <div class="editor-config-block-content-title" style="margin-bottom: 8px">
                  {{ item.title }}
                </div>
                <a-collapse default-active-key="0" :bordered="false" style="background: #fff">
                  <template #expandIcon="props">
                    <a-icon type="caret-right" class="colorIcons" :rotate="props.isActive ? 90 : 0" />
                  </template>
                  <a-collapse-panel :header="item2.name" :style="customStyle" v-for="(item2, index2) in item.children" :key="index2">
                    <div class="editor-config-block-content-tag-wrapper">
                      <div
                        class="editor-config-block-content-tag mb10"
                        v-for="(item3, index3) in item2.val"
                        :key="index3"
                        @click="handleVariable(item3.name)"
                      >
                        {{ item3.name }}
                      </div>
                    </div>
                  </a-collapse-panel>
                </a-collapse>
              </div>
              <div v-else>
                <div class="editor-config-block-content-title" :style="{ marginTop: index === 0 ? 0 : '15px' }">{{ item.title }}</div>
                <div class="editor-config-block-content-tag-wrapper">
                  <div
                    v-for="(tag, idx) in item.children"
                    :key="idx"
                    class="editor-config-block-content-tag"
                    @click="handleVariable(tag.name)"
                  >
                    {{ tag.name }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="ql-editor-footer footerBtnTemp" style="width: 100%; min-width: 1002px">
      <div>
        <a-button @click="$emit('upData', 0)"> 上一步</a-button>
      </div>
      <div>
        <a-button style="margin-right: 12px" @click="updateTemplate">设置默认印章位置</a-button>
        <a-button type="primary" @click="saveTemplate">保存</a-button>
      </div>
    </div>
    <preview :visible.sync="visible" :templateId="templateId" @close="visible = false" />
    <a-modal title="提示" :visible="tipsetVisible" :confirm-loading="confirmLoading" @ok="savafileSignDo" @cancel="cancelSavefileSignDo">
      <p style="font-weight: 500">确定要保存合同模板？</p>
    </a-modal>
  </div>
</template>
<script>
import vueWangeditor from "../../vueWangeditor";
import preview from "../../editSealNew/preview";
import {
  variableListAll,
  variableListAll2,
  templateUpdateReq,
  templateDetailReq,
  templateVariablesBatchReq,
  templateListAllReq,
  saveCategoryUpdate,
  updateTemplateVariableBySite
} from "@/api/company/contract";
import { isContainByString } from "@/utils/index";
export default {
  name: "Edit",
  watch: {
    content(text) {
      if (text.includes("<table>")) {
        this.content = text.replace("<table>", '<table border="1" cellpadding="0" cellspacing="0">');
      }
      if (text.includes('<table border="0"')) {
        this.content = text.replace('<table border="0"', '<table border="1"');
      }
      if (text.includes("<table style=")) {
        this.content = text.replace("<table style=", '<table border="1" cellpadding="0" cellspacing="0" style=');
      }
    }
  },
  components: {
    vueWangeditor,
    preview
  },
  data() {
    return {
      varQuery: "",
      isContainByString,
      templateId: null,
      template: null,
      name: "",
      menus: [
        "table", // 表格
        "bold", // 粗体
        "underline", // 下划线
        "italic", // 斜体
        "strikeThrough", // 中线
        "eraser", // 清空格式
        "foreColor", // 文字颜色
        "backColor", // 背景颜色
        "quote", // 引用
        "fontSize", // 字号
        "head", // 标题
        "list", // 无序列表
        "justify", // 有序列表
        "image", // 插入图片
        "undo", // 撤销
        "redo", // 重做
        "fullscreen"
      ],
      initContent: "",
      content: "",
      options: {},
      cursorPosition: null,
      variables: [],
      variableList: [],
      editorHeight: 0,
      customStyle: "background: #fff;border: 0;overflow: hidden;",
      footerBtnW: 0,
      personalVars: [],
      visible: false,
      tipsetVisible: false,
      confirmLoading: false,
      previewBtn: false
    };
  },
  created() {
    this.categoryId = this.$route.query.id;
    this.getTemplateListAllReq();
    this.loadVaribles();
    this.debouncedSearch = _.debounce(this.loadVaribles, 1000);
  },
  mounted() {
    if (document.getElementById("editor-main")) {
      this.editorHeight = document.getElementById("editor-main").offsetHeight - 20;
    }
  },
  methods: {
    loadVaribles() {
      const types = this.isContainByString("console");
      const companyId = this.isContainByString("console")
        ? null
        : this.isContainByString("contractAdmin")
        ? "site"
        : this.$store.state.hr.companyId;
      variableListAll2(
        {
          companyId,
          fieldName: this.varQuery
        },
        types
      )
        .then((res) => {
          const varibles = res.data;
          this.variableList = res.data;
          const jsonArr = [];
          const enterpriseVars = varibles.filter((item) => item.type === "enterprise");
          const contractVars = varibles.filter((item) => item.type === "contract");
          // 基本信息
          const basicArr = varibles.filter((item) => item.type === "basic");
          if (basicArr.length > 0) jsonArr.push({ name: "基本信息", val: basicArr });
          // 身份信息
          const empIdCardArr = varibles.filter((item) => item.type === "empIdCard");
          if (empIdCardArr.length > 0) jsonArr.push({ name: "身份信息", val: empIdCardArr });
          // 联系信息
          const contactArr = varibles.filter((item) => item.type === "contact");
          if (contactArr.length > 0) jsonArr.push({ name: "联系信息", val: contactArr });
          // 家庭成员
          const empFamilyArr = varibles.filter((item) => item.type === "empFamily");
          if (empFamilyArr.length > 0) jsonArr.push({ name: "家庭成员", val: empFamilyArr });
          // 紧急联系人
          const empContactsArr = varibles.filter((item) => item.type === "empContacts");
          if (empContactsArr.length > 0) jsonArr.push({ name: "紧急联系人", val: empContactsArr });
          // 教育经历
          const empEducationArr = varibles.filter((item) => item.type === "empEducation");
          if (empEducationArr.length > 0) jsonArr.push({ name: "教育经历", val: empEducationArr });
          // 自定义信息
          const additionalArr = varibles.filter((item) => item.type === "additional");
          if (additionalArr.length > 0) jsonArr.push({ name: "自定义信息", val: additionalArr });
          this.variables = [
            { title: "企业信息", children: enterpriseVars },
            { title: "员工个人信息", children: jsonArr },
            { title: "合同信息", children: contractVars }
          ];
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
      variableListAll()
        .then((res) => {
          this.personalVars = res.data.filter((item) => item.type === "personal");
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    async getTemplateListAllReq() {
      try {
        const { data } = await templateListAllReq(this.categoryId, this.$route.meta.pageType);
        this.loadTemplate(data[0].id);
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    loadTemplate(id) {
      this.templateId = id;
      templateDetailReq(id, this.$route.meta.pageType)
        .then((res) => {
          this.template = res.data;
          this.name = this.template.name;
          this.template.content = this.template.content || "";
          this.initContent = this.template.content.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
          this.content = this.template.content;
          this.$refs.editor.setHtml(this.initContent);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    saveTemplate() {
      this.tipsetVisible = true;
    },
    updateTemplate() {
      templateUpdateReq(
        Object.assign(this.template, {
          name: this.name,
          content: this.content,
          contentJson: this.content
        }),
        this.$route.meta.pageType
      )
        .then((res) => {
          this.updateTemplateVariables();
          this.$message.success("默认保存合同模板，正在跳转印章设置");
          if (this.$route.meta.pageType) {
            this.$router.push(`/console/tempContractTypeSeal/${this.templateId}`);
          } else {
            this.$router.push(`/${this.isContainByString("contractAdmin") ? "contractAdmin" : "contract"}/type/seal/${this.templateId}`);
          }
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          this.$message.error("合同模板更新失败");
        });
    },
    updateTemplateVariables() {
      const types = this.isContainByString("console") || this.isContainByString("contractAdmin");
      // 正则匹配
      // const regex1ARR = this.content.match(/#[A-Za-z0-9\u4e00-\u9fa5]+#/g) || [];
      // const regex2ARR = this.content.match(/#[\u4e00-\u9fa5]+\((.+?)\)+#/g) || [];
      // const regex3ARR = this.content.match(/#.*?#/g) || [];
      const varibleKeys = this.content.match(/>#.*?#</g) || [];
      if (varibleKeys && varibleKeys.length > 0) {
        const listTemp = varibleKeys.map((key) => {
          const keyTempL = key.replace(/>#/g, "");
          const keyTemp = keyTempL.replace(/#</g, "");
          const idx = this.variableList.findIndex((item) => item["name"] === keyTemp);
          const idx2 = this.personalVars.findIndex((item) => item["name"] === keyTemp);
          if (idx > -1) {
            return {
              templateId: this.templateId,
              variableId: this.variableList[idx]["id"],
              necessaryId: this.variableList[idx]["necessaryId"],
              additionalId: this.variableList[idx]["additionalId"],
              defaultId: this.variableList[idx]["defaultId"],
              personalVarId: idx2 !== -1 ? this.personalVars[idx2]["id"] : null
            };
          }
        });
        const json = {
          templateId: this.templateId,
          variableIds: [],
          necessaryIds: [],
          additionalIds: [],
          personalVarIds: [],
          defaultIds: []
        };
        listTemp.map((item) => {
          if (item) {
            const idx1 = json.variableIds.findIndex((it) => it === item.variableId);
            if (idx1 === -1 && item.variableId) {
              json.variableIds.push(item.variableId);
            }
            const idx2 = json.necessaryIds.findIndex((it) => it === item.necessaryId);
            if (idx2 === -1 && item.necessaryId) {
              json.necessaryIds.push(item.necessaryId);
            }
            const idx3 = json.additionalIds.findIndex((it) => it === item.additionalId);
            if (idx3 === -1 && item.additionalId) {
              json.additionalIds.push(item.additionalId);
            }
            const idx4 = json.personalVarIds.findIndex((it) => it === item.personalVarId);
            if (idx4 === -1 && item.personalVarId) {
              json.personalVarIds.push(item.personalVarId);
            }
            const idx5 = json.defaultIds.findIndex((it) => it === item.defaultId);
            if (idx5 === -1 && item.defaultId) {
              json.defaultIds.push(item.defaultId);
            }
          }
        });
        json.variableIds = [...json.variableIds, ...json.personalVarIds];
        delete json.defaultIds;
        delete json.personalVarIds;
        if (this.isContainByString("contractAdmin")) {
          updateTemplateVariableBySite(json, types)
            .then((res) => {})
            .catch((err) => {
              console.log("debug log --> ", err);
            });
        } else {
          templateVariablesBatchReq(json, types)
            .then((res) => {})
            .catch((err) => {
              console.log("debug log --> ", err);
            });
        }
      }
    },
    back() {
      this.$router.go(-1);
    },
    handleVariable(text) {
      this.insertVariable(text);
    },
    getCursorPosition() {
      this.$refs.editor.quill.focus();
      const range = this.$refs.editor.quill.getSelection();
      this.cursorPosition = range.index;
    },
    insertVariable(text) {
      this.$refs.editor.insertHtml("<span>&nbsp;</span>");
      const tempText = `<a style="color: #6A66F6; text-decoration: underline">#${text}#</a>`;
      this.$refs.editor.insertHtml(tempText);
      this.$refs.editor.insertHtml("<span>&nbsp;</span>");
    },
    onPreview() {
      this.previewBtn = true;
      templateUpdateReq(
        Object.assign(this.template, {
          name: this.name,
          content: this.content,
          contentJson: this.content
        }),
        this.$route.meta.pageType
      )
        .then((res) => {
          this.updateTemplateVariables();
          this.previewBtn = false;
          this.visible = true;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          this.previewBtn = false;
          this.$message.error("合同模板更新失败");
        });
    },
    savefileSign() {
      this.fileForm.validateFields((err, values) => {
        if (!err) {
          this.tipsetVisible = true;
        }
      });
    },
    cancelSavefileSignDo() {
      this.tipsetVisible = false;
    },
    savafileSignDo(e) {
      e.preventDefault();
      this.confirmLoading = true;
      templateUpdateReq(
        Object.assign(this.template, {
          name: this.name,
          content: this.content,
          contentJson: this.content
        }),
        this.$route.meta.pageType
      )
        .then((res) => {
          this.updateTemplateVariables();
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          this.confirmLoading = false;
        });
      const categoryUpdateDTOFront = JSON.parse(sessionStorage.getItem("categoryUpdateDTO"));
      const types = this.isContainByString("console") || this.isContainByString("contractAdmin");
      var categoryUpdateDTO = {
        ...categoryUpdateDTOFront,
        id: this.$route.query.id,
        groupId: this.$route.query.groupId,
        subjectId: types ? "0" : this.$store.state.hr.companyId,
        name: sessionStorage.getItem("contractTypeQueryName")
      };
      if (this.isContainByString("contractAdmin")) categoryUpdateDTO.isSiteUpdate = true;

      saveCategoryUpdate(categoryUpdateDTO, this.$route.meta.pageType)
        .then((res) => {
          this.$message.success("保存成功");
          this.$router.go(-1);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          this.confirmLoading = false;
          this.$message.error("合同模板更新失败");
        });
    }
  }
};
</script>
<style lang="scss">
.ql-editor-wrapperStyle {
  .editor-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 24px;
    .labels {
      height: 20px;
      line-height: 20px;
      font-size: 16px;
      font-weight: 400;
      color: #252525;
      position: relative;
      padding-left: 12px;
      p {
        position: absolute;
        top: 0;
        left: 0;
        width: 3px;
        height: 20px;
        background: #6a66f6;
        border-radius: 2px;
      }
    }
    .tips {
      font-size: 14px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.25);
      line-height: 12px;
      margin-bottom: 14px;
    }
  }

  .ql-editor-wrapper .editor-main .quill-editor .ql-container .ql-editor {
    height: calc(100vh - 410px) !important;
    overflow: auto;
  }

  .ql-editor-content2 {
    width: 100%;
    height: calc(100vh - 400px) !important;
    padding-right: 0 !important;
  }

  .editor-config2 {
    height: calc(100vh - 400px) !important;
  }

  #editor-main {
    width: calc(100% - 290px);
    height: calc(100vh - 400px) !important;
    overflow: auto;
    margin: 0;
  }
  .ql-editor-header {
    display: flex;
    align-items: center;
    height: 60px;
  }
  .colorIcons {
    color: var(--primary) !important;
  }
  .ant-collapse-header {
    margin-left: -16px;
    padding-left: 32px !important;
    padding-top: 4px !important;
    padding-bottom: 4px !important;
  }
  .ant-collapse-content-box {
    padding: 4px !important;
  }
  .mb10 {
    margin-top: 0 !important;
    margin-bottom: 10px !important;
  }
  .footerBtnTemp {
    position: sticky;
    left: 0;
    bottom: 0;
    width: 100%;
    background: #fff;
    z-index: 20;
    display: flex;
    justify-content: space-between;
  }
}
</style>
